# -*- coding: utf-8 -*-
"""
用户模型
@api-version: 1.0.0
"""

from datetime import datetime
from . import db
import bcrypt

class User(db.Model):
    """用户模型"""
    __tablename__ = 'users'
    
    id = db.Column(db.Integer, primary_key=True, comment='用户ID')
    username = db.Column(db.String(50), unique=True, nullable=False, comment='用户名（已废弃，保留兼容性）')
    nickname = db.Column(db.String(50), unique=True, nullable=False, comment='昵称')
    email = db.Column(db.String(100), unique=True, nullable=False, comment='邮箱')
    password_hash = db.Column(db.String(255), nullable=False, comment='密码哈希')
    real_name = db.Column(db.String(50), comment='真实姓名')
    phone = db.Column(db.String(20), comment='手机号')
    role = db.Column(db.Enum('admin', 'user', name='user_role'), 
                    nullable=False, default='user', comment='用户角色')
    status = db.Column(db.Integer, nullable=False, default=1, comment='状态：1-正常，0-禁用')
    # 文件上传权限控制
    can_upload_files = db.Column(db.Boolean, nullable=False, default=False, 
                                comment='是否允许上传实际文件：False-仅MD5秒传，True-允许实际上传')
    # nickname_updated_at 字段已移除，使用 updated_at 统一管理更新时间
    last_login = db.Column(db.DateTime, comment='最后登录时间')
    created_at = db.Column(db.DateTime, nullable=False, default=datetime.utcnow, comment='创建时间')
    updated_at = db.Column(db.DateTime, nullable=False, default=datetime.utcnow, 
                          onupdate=datetime.utcnow, comment='更新时间')
    
    # 关联关系
    sessions = db.relationship('UserSession', backref='user', lazy='dynamic', 
                              cascade='all, delete-orphan')
    
    def __init__(self, email, password, nickname=None, role='user', real_name=None, phone=None):
        self.username = email  # 保持兼容性，使用邮箱作为用户名
        self.nickname = nickname or email.split('@')[0]  # 默认使用邮箱前缀作为昵称
        self.email = email
        self.set_password(password)
        self.role = role
        self.real_name = real_name
        self.phone = phone
        # 昵称更新时间现在使用 updated_at 统一管理
    
    def set_password(self, password):
        """设置密码"""
        salt = bcrypt.gensalt()
        self.password_hash = bcrypt.hashpw(password.encode('utf-8'), salt).decode('utf-8')
    
    def check_password(self, password):
        """验证密码"""
        return bcrypt.checkpw(password.encode('utf-8'), self.password_hash.encode('utf-8'))
    
    def is_admin(self):
        """判断是否为管理员"""
        return self.role == 'admin'
    
    def is_active(self):
        """判断账户是否激活"""
        return self.status == 1
    
    def can_update_nickname(self):
        """检查是否可以修改昵称（每年限制一次）"""
        if not self.updated_at:
            return True
        
        from datetime import timedelta
        from utils.datetime_utils import get_local_now
        one_year_ago = get_local_now() - timedelta(days=365)
        return self.updated_at <= one_year_ago
    
    def update_nickname(self, new_nickname):
        """更新昵称并记录时间"""
        self.nickname = new_nickname
        # updated_at 会自动更新，无需手动设置
    
    def to_dict(self, include_sensitive=False):
        """转换为字典"""
        data = {
            'id': self.id,
            'username': self.username,  # 保留兼容性
            'nickname': self.nickname,
            'email': self.email,
            'realName': self.real_name,
            'phone': self.phone,
            'role': self.role,
            'status': self.status,
            'canUploadFiles': self.can_upload_files,  # 文件上传权限
            # nicknameUpdatedAt 字段已移除，使用 updatedAt 统一管理
            'lastLogin': self.last_login.isoformat() if self.last_login else None,
            'createdAt': self.created_at.isoformat() if self.created_at else None,
            'updatedAt': self.updated_at.isoformat() if self.updated_at else None
        }
        
        if include_sensitive:
            data['passwordHash'] = self.password_hash
        
        return data
    
    def __repr__(self):
        return f'<User {self.username}>'